# -*- makefile -*-

# $(1) = fiasco
# $(2) = fiasco.debug
# $(3) = symbol of section begin
# $(4) = symbol of section end
define get_checksum
$(OBJDUMP) \
  `$(NM) $(2)|sed -n \
    's/\([[:xdigit:]]\+\) *. *\<$(3)\>/--start-address=0x\1/p; \
     s/\([[:xdigit:]]\+\) *. *\<$(4)\>/--stop-address=0x\1/p'` \
  -s $(1) | cut -f3,4,5,6 -d' ' | ./genchecksum
endef

# Generate targets for checksumming and accumulate them as $(CHECKSUM):
# prerequisites.
#  $(1) = fiasco - variable
#  $(2) = fiasco.debug - variable
#  $(3) = target suffix, e.g. unit test name
define all_checksum_rules =

do_chksum$(3): setchecksum genchecksum $(1)
	$$(PATCH_MESSAGE)"$(1)"
	$$(VERBOSE)\
	  cscode=$$$$($$(call get_checksum,$(1),$(2),_start,_etext)); \
	  csdata=$$$$($$(call get_checksum,$(1),$(2),_kernel_data_start,_edata)); \
	  ./setchecksum $(1) 0x$$$$cscode 0x$$$$csdata && echo done > $$@
	$$(call INSTALLFILE_RULE,fiasco,fiasco)

$$(CHECKSUM): do_chksum$(3)

endef

# generate checksum targets for normal kernel build
$(eval $(call all_checksum_rules,$(BOOT),$(KERNEL)))


setchecksum: setchecksum.c
	$(COMP_MESSAGE)
	$(VERBOSE)$(HOST_CC) $(HOST_CPPFLAGS) $(HOST_CFLAGS) -o $@ $^

genchecksum: genchecksum.cc
	$(COMP_MESSAGE)
	$(VERBOSE)$(HOST_CXX) -fno-rtti -fno-exceptions $(HOST_CPPFLAGS) $(HOST_CXXFLAGS) -o $@ $^

clean-CHECKSUM:
	$(VERBOSE)$(RM) genchecksum setchecksum do_chksum* checksum.ro* checksum.rw*

